//
//  PopulationContainerViewController.m
//  Utils
//
//  Created by enghou on 2018/4/20.
//  Copyright © 2018年 xyxorigation. All rights reserved.
//

#import "PopulationContainerViewController.h"
@interface PopulationContainerViewController ()<ChangePage,UIPageViewControllerDelegate,UIPageViewControllerDataSource,UIScrollViewDelegate>

@end

@implementation PopulationContainerViewController

-(NSMutableDictionary *)param{
    PopulationBaseInfoViewController *p = _ctlArray[0];
    PopulationRegisterViewController *po = _ctlArray[1];
    QueryTypeSelectionController *query = _ctlArray[2];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    if ([p param] && [po param] && [query param]) {
        [param addEntriesFromDictionary:[p param]];
        [param addEntriesFromDictionary:[po param]];
        [param addEntriesFromDictionary:[query param]];
    }else{
        return nil;
    }
    return param;
}

-(void)loadData{
    if ([self.ids length] > 0) {
        [self beginLoading];
        [[NetWorkerManager sharedInstance]getHousingInfoWithId:self.ids successBlock:^(BaseModel *model) {
            [self endLoading];
            if (model.success) {
                NSDictionary *data = [model.data objectForKey:@"data"];
                PopulationBaseInfoViewController *p = [self.ctlArray objectAtIndex:0];
                NSLog(@"%@",p.view);
                if (data[@"imgUrl"]) {
                    p.head_imageurl = [NSString stringWithFormat:@"%@/%@",ServerPath,data[@"imgUrl"]];
                    [p.headImageView sd_setImageWithURL:[NSURL URLWithString:p.head_imageurl] placeholderImage:[UIImage imageNamed:@"icon_empty_head"]];
                }
                p.idCardField.text = data[@"idCardNo"];
                if ([data[@"idCardNo"] length] == 18) {
                    p.idCardField.enabled = NO;
                }
                p.nameField.text = data[@"name"];
                p.sexField.text = data[@"gender"][@"displayName"];
                p.sexModel = [[PropertyDictItemModel alloc]init];
                p.sexModel.ids = [model contentForKey:@"id" withSource:data[@"gender"]];
                p.sexModel.displayName = [model contentForKey:@"displayName" withSource:data[@"gender"]];//data[@"gender"][@"displayName"];
                p.birthdayField.text = data[@"birthday"];
                p.locateTypeField.text = data[@"residenceType"][@"displayName"];
                p.registerTypeModel = [[PropertyDictItemModel alloc]init];
                p.registerTypeModel.displayName = data[@"residenceType"][@"displayName"];
                p.registerTypeModel.ids = [model contentForKey:@"id" withSource:data[@"residenceType"]];
                p.minzuField.text = data[@"nation"][@"displayName"];
                p.minzuModel = [[PropertyDictItemModel alloc]init];
                p.minzuModel.ids = [model contentForKey:@"id" withSource:data[@"nation"]];
                p.minzuModel.displayName = data[@"nation"][@"displayName"];
                p.hujiProvince = [[Province alloc]init];
                p.hujiProvince.code = [model contentForKey:@"province" withSource:data];//data[@"province"];
                p.hujiCity = [[City alloc]init];
                p.hujiCity.code = [model contentForKey:@"city" withSource:data];;
                p.hujiCountry = [[Country alloc]init];
                p.hujiCountry.code = [model contentForKey:@"district" withSource:data];;
                p.oldProvince = [[Province alloc]init];
                p.oldProvince.code = [model contentForKey:@"placeProvince" withSource:data];;
                p.oldCity = [[City alloc]init];
                p.oldCity.code = [model contentForKey:@"placeCity" withSource:data];
                p.oldCountry = [[Country alloc]init];
                p.oldCountry.code = [model contentForKey:@"placeDistrict" withSource:data];
                
                p.nowProvince = [[Province alloc]init];
                p.nowProvince.code = [model contentForKey:@"presentProvince" withSource:data];
                p.nowCity = [[City alloc]init];
                p.nowCity.code = [model contentForKey:@"presentProvince" withSource:data];
                p.nowCountry = [[Country alloc]init];
                p.nowCountry.code = [model contentForKey:@"presentProvince" withSource:data];
                
                p.politicalModel = [[PropertyDictItemModel alloc]init];
                p.politicalModel.ids = [model contentForKey:@"id" withSource:data[@"politicalBackground"]];
                
                p.marryModel = [[PropertyDictItemModel alloc]init];
                p.marryModel.ids = [model contentForKey:@"id" withSource:data[@"maritalState"]];
                
                p.eduDegreeModel = [[SubTypeItemModel alloc]init];
                p.eduDegreeModel.subTid = [model contentForKey:@"schoolVal" withSource:data];//data[@"schoolVal"];
                p.educationDegreeField.text = data[@"schoolStr"];
                
                p.occupyModel = [[PropertyDictItemModel alloc]init];
                p.occupyModel.ids = [model contentForKey:@"id" withSource:data[@"career"]];//data[@"career"][@"id"];
                
                p.religionModel = [[PropertyDictItemModel alloc]init];
                p.religionModel.ids = [model contentForKey:@"id" withSource:data[@"faith"]];
                
                p.zhengzhiField.text = data[@"politicalBackground"][@"displayName"];
                p.marriedField.text = data[@"maritalState"][@"displayName"];
                p.locateAddressField.text = data[@"domicilePlace"];
                p.homeLocateField.text = data[@"place"];
                p.homeLocateDetailField.text = data[@"nativePlaceAddress"];
                BOOL hasHouse = [data[@"isHaveHouse"] boolValue];
                p.nowLocateField.text = data[@"present"];
                if (hasHouse) {
//                    p.yesBtn.enabled = YES;
                    p.yesBtn.selected = YES;
                    p.noBtn.selected = NO;
                    p.nowLocateDetailField.text = data[@"currentAddress"];
                    NSMutableAttributedString *target = [[NSMutableAttributedString alloc]initWithString:@"*现住门(楼)详址" attributes:@{NSForegroundColorAttributeName:[UIColor blackColor],NSFontAttributeName:[UIFont systemFontOfSize:17]}];
                    [target addAttributes:@{NSForegroundColorAttributeName:[UIColor redColor],NSFontAttributeName:[UIFont fontWithName:@"Helvetica" size:17.f]} range:NSMakeRange(0, 1)];
                    p.nowLocateDetailField.placeholder = @"请输入门楼详址";
                    p.changeState.attributedText = target;
                }else{
//                    p.noBtn.enabled = YES;
                    p.noBtn.selected = YES;
                    p.yesBtn.selected = NO;
                    p.nowLocateDetailField.text = data[@"noHouseReason"];
                    NSMutableAttributedString *target = [[NSMutableAttributedString alloc]initWithString:@"*无住房原因" attributes:@{NSForegroundColorAttributeName:[UIColor blackColor],NSFontAttributeName:[UIFont fontWithName:@"Helvetica" size:17.f]}];
                    [target addAttributes:@{NSForegroundColorAttributeName:[UIColor redColor],NSFontAttributeName:[UIFont systemFontOfSize:17]} range:NSMakeRange(0, 1)];
                    p.changeState.attributedText = target;
                    p.nowLocateDetailField.placeholder = @"请输无住房原因";
                }
                p.marriedField.text = data[@"maritalState"][@"displayName"];
                p.pastNameField.text = data[@"usedName"];
                p.phoneNumberField.text = [model contentForKey:@"mobileNumber" withSource:data];//data[@"mobileNumber"];
                p.stablePhoneField.text = [model contentForKey:@"telephone" withSource:data];//data[@"telephone"];
                p.occupyCategoryField.text = data[@"career"][@"displayName"];
                p.occupyField.text = data[@"careerText"];
                p.zongjiaoField.text = data[@"faith"][@"displayName"];
                p.serviceLocateField.text = data[@"workUnit"];
                PopulationRegisterViewController *po = self.ctlArray[1];
                NSLog(@"%@",po.view);
                po.homeNumberField.text = [model contentForKey:@"accountNumber" withSource:data];
                po.relationLabel.text = data[@"relationShipWithHead"][@"displayName"];
                po.relationModel = [[PropertyDictItemModel alloc]init];
                po.relationModel.ids = [model contentForKey:@"id" withSource:data[@"relationShipWithHead"]];
                po.stateLabel.text = data[@"residentStatus"][@"displayName"];
                po.stateModel = [[PropertyDictItemModel alloc]init];
                po.stateModel.ids = data[@"residentStatus"][@"id"];
                QueryTypeSelectionController *query = self.ctlArray[2];
                
                NSLog(@"%@",query.view);
                NSMutableArray *selectedBusiness = [data[@"businessInformationPerson"] mutableCopy];
                NSArray *selectOrgs = data[@"railways"];
                if ([selectOrgs count] > 0) {
                    NSDictionary *firstOrg = selectOrgs[0];
                    [selectedBusiness enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                        if ([obj isEqualToString:@"alongRailwayPeople"]) {
                            [selectedBusiness removeObject:obj];
                        }
                    }];
                    query.selectedOrgId = firstOrg[@"orgId"];
                    query.orgType = firstOrg[@"type"];
                }
                query.selectedBusiness = [selectedBusiness mutableCopy];
            }else{
                [self alertSome:model.msg];
            }
        } failBlock:^(NSInteger code) {
            [self endLoading];
            [self alertSome:kNetWorkFail];
        }];
    }
}

-(void)editAction{
    [self submitAction];
}

-(void)deleAction{
    if ([self.ids length] > 0) {
        [self beginLoading];
        [[NetWorkerManager sharedInstance]deletePersonWithId:self.ids successBlock:^(BaseModel *model) {
            [self endLoading];
            if (model.success) {
                [(BaseViewController *)self.theDelete performSelector:@selector(beginRefresh)];
                [self.navigationController popToViewController:(UIViewController *)self.theDelete animated:YES];
            }else{
                [self alertSome:model.msg];
            }
        } failBlock:^(NSInteger code) {
            [self endLoading];
            [self alertSome:kNetWorkFail];
        }];
    }
}

-(void)addNewWithFilePath:(NSString *)path{
    NSMutableDictionary *param = [self param];
    if (param) {
        if (path) {
            [param setObject:path forKey:@"population.fileStorage.path"];
        }
        [self beginLoading];
        [[NetWorkerManager sharedInstance]addNewPeopleInfoWithParam:param successBlock:^(BaseModel *model) {
            [self endLoading];
            if (model.success) {
                [self.theDelete performSelector:@selector(beginRefresh)];
                [self.navigationController popToViewController:(UIViewController *)self.theDelete animated:YES];
            }else{
                [self alertSome:model.msg];
            }
        } failBlock:^(NSInteger code) {
            [self endLoading];
            [self alertSome:kNetWorkFail];
        }];
    }
}

-(void)modifyWithFilePath:(NSString *)path{
    NSMutableDictionary *param = [self param];
    if (param) {
        if (path) {
            [param setObject:path forKey:@"population.fileStorage.path"];
        }
        [self beginLoading];
        [[NetWorkerManager sharedInstance]updatePeopleInfoWithParam:param successBlock:^(BaseModel *model) {
            [self endLoading];
            if (model.success) {
                [self.theDelete performSelector:@selector(beginRefresh)];
                [self pop];
            }else{
                [self alertSome:model.msg];
            }
        } failBlock:^(NSInteger code) {
            [self endLoading];
            [self alertSome:kNetWorkFail];
        }];
    }
}

-(void)submitAction{
    if (self.ids) {
        PopulationBaseInfoViewController *p = _ctlArray[0];
        if (p.headImage) {
            NSData *data = UIImageJPEGRepresentation(p.headImage, 0.1);
            [self uploadImage:data successBlock:^(NSString *filePath) {
                [self modifyWithFilePath:filePath];
            }];
        }else{
            [self modifyWithFilePath:nil];
        }
    }else{
        PopulationBaseInfoViewController *p = _ctlArray[0];
        if (p.headImage) {
            NSData *data = UIImageJPEGRepresentation(p.headImage, 0.1);
            [self uploadImage:data successBlock:^(NSString *filePath) {
                [self addNewWithFilePath:filePath];
            }];
        }else{
            [self addNewWithFilePath:nil];
        }
    }
}

-(void)uploadImage:(NSData *)image successBlock:(void(^)(NSString *))suc{
    [self beginLoading];
    [[NetWorkerManager sharedInstance]uploadImageWithPath:kUploadFilePath parameter:nil files:@[image] fileName:@"file" suffix:@"jpg" completeBlock:^(NSDictionary *source) {
        [self endLoading];
        BaseModel *model = [[BaseModel alloc]initWithSourceDict:source listItemClass:NSClassFromString(@"FileItemModel")];
        if (model.success) {
            FileItemModel *file = model.list[0];
            suc(file.path);
        }
    } failBlock:^(NSInteger code) {
        [self endLoading];
        [self alertSome:kNetWorkFail];
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadData];
    if (self.ids) {
        //修改
        UIBarButtonItem *edit = [[UIBarButtonItem alloc]initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(submitAction)];
        edit.tintColor = [UIColor whiteColor];
        UIBarButtonItem *delete = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemTrash target:self action:@selector(deleAction)];
        delete.tintColor = [UIColor whiteColor];
        self.navigationItem.rightBarButtonItems = @[delete,edit];
    }else{
        //新增
        UIBarButtonItem *submit = [[UIBarButtonItem alloc]initWithTitle:@"提交" style:UIBarButtonItemStylePlain target:self action:@selector(submitAction)];
        submit.tintColor = [UIColor whiteColor];
        self.navigationItem.rightBarButtonItem = submit;
    }
    
    self.slide = [[SlidePageView alloc]initWithFrame:CGRectMake(0, 0, self.view.width, 40)];
    self.slide.layer.borderColor = [[UIColor defaultBackgroundColor]CGColor];
    self.slide.layer.borderWidth = 1;
    [self.slide configTitles:@[@"基本信息",@"户籍信息",@"业务信息"]];
    _slide.delegate = self;
    self.slide.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.slide];
    
    self.page = [[UIPageViewController alloc]initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:nil];
    self.page.delegate = self;
    self.page.dataSource = self;
    for(id subview in _page.view.subviews){
        if([subview isKindOfClass:UIScrollView.class]){
            [subview performSelector:@selector(setDelegate:) withObject:self];
            break;
        }
    }
    self.page.view.frame = CGRectMake(0, 40, self.view.width, ScreenHeight - 40);
    [self.view addSubview:self.page.view];
    self.ctlArray = [NSMutableArray array];
    [self configViewControllers];
}

-(void)configViewControllers{
    PopulationBaseInfoViewController *p = (PopulationBaseInfoViewController *)[VCLoader vcWithName:@"PopulationBaseInfoViewController"];
    p.theDelete = self;
    p.ids = self.ids;
    p.canEdit = YES;
    [self.ctlArray addObject:p];
    PopulationRegisterViewController *pr = (PopulationRegisterViewController *)[VCLoader vcWithName:@"PopulationRegisterViewController"];
    pr.theDelete = self;
    pr.canEdit = YES;
    [self.ctlArray addObject:pr];
    QueryTypeSelectionController *vc = (QueryTypeSelectionController *)[VCLoader vcWithName:@"QueryTypeSelectionController"];
    vc.multiSelect = YES;
    vc.theDelete = self;
    vc.path = kPeopleKind;
    vc.cantEdit = NO;
    vc.itemCls = @"PeopleListModel";
    [self.ctlArray addObject:vc];
    [self.page setViewControllers:@[self.ctlArray[0]] direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.translucent = NO;
}

-(void)changeToPage:(NSInteger)idx{
    NSInteger currentIdx = [_ctlArray indexOfObject:_page.viewControllers[0]];
    if ([_ctlArray count] > idx) {
        __weak PopulationContainerViewController *wself = self;
        if (idx > currentIdx) {
            [_page setViewControllers:@[_ctlArray[idx]] direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:^(BOOL finished) {
                [wself.slide unlockForRespondsToScroll];
            }];
        }else if (idx < currentIdx){
            [_page setViewControllers:@[_ctlArray[idx]] direction:UIPageViewControllerNavigationDirectionReverse animated:YES completion:^(BOOL finished) {
                [wself.slide unlockForRespondsToScroll];
            }];
        }
    }
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGFloat x = scrollView.contentOffset.x;
    if (x > ScreenWidth) {
        //让滑条做相应位移
        [_slide slideToOffset:x-ScreenWidth];
    }else if (x < ScreenWidth){
        [_slide slideToOffset:x-ScreenWidth];
    }
}

-(UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController{
    NSInteger idx = [_ctlArray indexOfObject:viewController];
    if (idx == [_ctlArray count] - 1) {
        return nil;
    }else{
        return [_ctlArray objectAtIndex:idx+1];
    }
}

-(void)turnToIndex:(NSInteger)index andAlert:(NSString *)msg{
    [self.page setViewControllers:@[_ctlArray[index]] direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil];
    [self.slide slideToPosition:index];
    BaseViewController *vc = _ctlArray[index];
    [vc alertSome:msg];
}

-(UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController{
    NSInteger idx = [_ctlArray indexOfObject:viewController];
    if (idx == 0) {
        return nil;
    }else{
        return [_ctlArray objectAtIndex:idx - 1];
    }
}

-(void)pageViewController:(UIPageViewController *)pageViewController didFinishAnimating:(BOOL)finished previousViewControllers:(NSArray<UIViewController *> *)previousViewControllers transitionCompleted:(BOOL)completed{
    if (finished) {
        if (completed) {
            NSInteger idx = [_ctlArray indexOfObject:pageViewController.viewControllers[0]];
            [self.slide slideToPosition:idx];
            [self.slide unlockForRespondsToScroll];
        }
    }
}

@end
